package com.roc.web.action.agent;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitModule;
import com.roc.pojo.ProfitPercent;
import com.roc.pojo.ProfitRule;
import com.roc.pojo.TblInsInf;
import com.roc.service.IAgentService;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IModelService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.agent.IAgentInfoService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.Utils;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.InvoiceRateType;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.SexStatus;

/**
 * 代理商查询
 * 
 *
 */

@Component
@Scope("prototype")
@Namespace("/agentQuery")
public class AgentUnQueryAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(AgentQueryAction.class);
	
	private AgentUnQuerySearchCondition searchCondition;
	
	private SerialNumQueryCondition serialNumCondition;
	
	private Operators merchant;
	
	private AuditingItem auditing;
	
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	
	private List<Operators> operatorsList=new ArrayList<Operators>();
	
	private String code;
	
	private String updateFlag;

	private InputStream excelFile;
	private String  excelName;
	
	@Autowired
	IorgService orgService;
	
	@Autowired
	IPageService pagenitionService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IPowerInfoService powerInfoService;
	
	@Autowired
	IAgentInfoService agentInfoService;
	@Autowired
	IMerchantServices merinfoService;
	@Autowired
	IAgentService  agentService;
	@Autowired
	IModelService modelService;

	@Autowired
	IExcelService excelService;
	
	private Operators agent;
	
	
	@Action(value = "queryAgentUnListJsp", results = { @Result(name = "success", location = "/pages/agent/agentUnList.jsp")
             })
	public String queryAgentUnListJspAction() throws Exception{
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		// 如果当前登录账号是 商户/业务员/收付宝，没有权限登陆
		if( logingMerchant.getRoleType().equals(Role.MERCHANT.getCode()) 
				|| logingMerchant.getRoleType().equals(Role.AGENT_BUSS.getCode())
				 || logingMerchant.getRoleType().equals(Role.SFB_AGENT.getCode()) 
				 || logingMerchant.getRoleType().equals(Role.AGENT.getCode()) ){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		org();
		
		return SUCCESS;
	}
	
	@Action(value = "queryAgentUnListInfo", results = { @Result(name = "success", location = "/pages/agent/agentUnList.jsp")
           })
	//查询代理商
	public String queryAgentUnListInfoAction() throws Exception{
		
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
        
        
		
		if(searchCondition==null){
			searchCondition=(AgentUnQuerySearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new AgentUnQuerySearchCondition();
			}
		}
		try {
			// 如果当前登录账号是 商户/业务员/收付宝，没有权限登陆
			if( logingMerchant.getRoleType().equals(Role.MERCHANT.getCode()) 
					|| logingMerchant.getRoleType().equals(Role.AGENT_BUSS.getCode())
					 || logingMerchant.getRoleType().equals(Role.SFB_AGENT.getCode()) 
					 || logingMerchant.getRoleType().equals(Role.AGENT.getCode()) ){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();

			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
            String orgCode=map.get("orgCode");
            String superRole= map.get("superRole");
            String opRealId =map.get("opRealId");
            if("99".equals(searchCondition.getOrgCode())){
            	searchCondition.setOrgCode(orgCode);//当前查询人员所属机构
            }
            searchCondition.setRoleId(superRole);// 角色
            searchCondition.setAgentId(opRealId);//当前人员id
            searchCondition.setOneOrgCode( logingMerchant.getOneagentid() );// 一级机构编号
            // 受理市场标识
            searchCondition.setGroupCdFlag( map.get("groupCd") );
       //     searchCondition.setOrgCode(orgCode);;//当前人员id
   		
			
	/*		
			//查询所属代理商
	        if(logingMerchant.getRoleType().equals(Role.AGENT.getCode())){
	        	operatorsList=merchantServices.listOperatorsAgent(logingMerchant.getOrgCode());
	        }else{
	        	operatorsList=merchantServices.listOperatorsAgent(null);
	        }*/
/*			if(searchCondition.getRole().equals("99")){
				searchCondition.setRole(Role.AGENT.getCode()+","+Role.O_MANAGER.getCode());   //操作员类型查询  代理商  和  O单管理员
			}
*/
		/*	// 如果只查询直属代理商
			if(searchCondition.getIsDirectly().equals("0")){
				   searchCondition.setOpId(opRealId);
			}*/
			//当登录人员为代理商时，查询他的子代理
	/* 暂时屏蔽		if(logingMerchant.getRoleType().equals(Role.AGENT.getCode()) || logingMerchant.getRoleType().equals(Role.AGENT_BUSS.getCode())){
				String agentId= String.valueOf(logingMerchant.getId());
				searchCondition.setAgentId(agentId);
			} */
			//searchCondition.setStatus(OperatorsStatus.WAIT_AUDITING.getCode());  //查询代理商状态为  待审核   的
/*			searchCondition.setOperators(logingMerchant);*/

			String invoiceRateFlag = "0";
			// 如果当前登陆账号/上级账号是系统管理员 , 或 登陆账号是 市场人员 ，则允许显示发票扣率
			if(superRole.equals(Role.SYSTEM.getCode()) 
					|| superRole.equals(Role.MARKET_DIRECT.getCode())
					|| superRole.equals(Role.MARKET_LEAD.getCode())
					){
				invoiceRateFlag = "1";
			}
			getRequest().setAttribute("invoiceRateFlag", invoiceRateFlag);
			
			int rows=pagenitionService.countSQL(searchCondition);
			searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			 List<Object> searchRsList1=new ArrayList<Object>() ;
			
			
			if (searchRsList != null && searchRsList.size() > 0) {
				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					Operators sett = new Operators();
					if (obj[0] != null && !"".equals(obj[0])) {
						sett.setId(Long.valueOf(obj[0].toString()));
					}
					
					if (obj[1] != null && !"".equals(obj[1])) {
						sett.setAccountNo(obj[1].toString());
					}
					if (obj[2] != null && !"".equals(obj[2])) {
						sett.setRealName(obj[2].toString());
					}
					if (obj[3] != null && !"".equals(obj[3])) {
						sett.setSex(obj[3].toString());
					}
					if (obj[4] != null && !"".equals(obj[4])) {
						sett.setMobile(obj[4].toString());
					}
					if (obj[5] != null && !"".equals(obj[5])) {
						sett.setOrgCode(obj[5].toString());
					}
					if (obj[6] != null && !"".equals(obj[6])) {
						sett.setRoleType(obj[6].toString());
					}
					if (obj[7] != null && !"".equals(obj[7])) {
						sett.setSuperiorId(Long.valueOf(obj[7].toString()));
					}
					if (obj[8] != null && !"".equals(obj[8])) {
						sett.setCardNo(obj[8].toString());
					}
					if (obj[9] != null && !"".equals(obj[9])) {
						sett.setStatus(obj[9].toString());
					}
					/*
					if (obj[10] != null && !"".equals(obj[10])) {
						sett.setCompanyid(obj[10].toString());
					}
					if (obj[11] != null && !"".equals(obj[11])) {
						sett.setOneagentid(obj[11].toString());
					}*/
					if (obj[12] != null && !"".equals(obj[12])) {
						sett.setTaxRegistrationCertificate(InvoiceRateType.valueOfCode(obj[12].toString()).getName()); // 发票扣率
					}
					if (obj[13] != null && !"".equals(obj[13])) {
						sett.setOrganizationCode(obj[13].toString()); // 序号编码
					}
					if (obj[14] != null && !"".equals(obj[14])) {
						sett.setSuperiorName(obj[14].toString());
					}
					if (obj[15] != null && !"".equals(obj[15])) {
						sett.setCompanyName(obj[15].toString());
					}
					if (obj[16] != null && !"".equals(obj[16])) {
						sett.setOneagentName(obj[16].toString());
					}
					searchRsList1.add(sett);
				}
			}
			agentTheListSpecially(searchRsList1);
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	@Action(value="excelAgentUnListInfo",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
 "bufferSize", "1024*3" }),@Result(name="error",location="/pages/agent/agentUnList.jsp") }) 
	//查询代理商
	public String excelAgentUnListInfo() throws Exception{
		
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		String reportName = "代理商信息导出";
		try {

			// 如果当前登录账号是 商户/业务员/收付宝，没有权限登陆
			if( logingMerchant.getRoleType().equals(Role.MERCHANT.getCode()) 
					|| logingMerchant.getRoleType().equals(Role.AGENT_BUSS.getCode())
					 || logingMerchant.getRoleType().equals(Role.SFB_AGENT.getCode())
					 || logingMerchant.getRoleType().equals(Role.AGENT.getCode()) ){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();

			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
            String orgCode=map.get("orgCode");
            String superRole= map.get("superRole");
            String opRealId =map.get("opRealId");
            if("99".equals(searchCondition.getOrgCode())){
            	searchCondition.setOrgCode(orgCode);//当前查询人员所属机构
            }
            searchCondition.setRoleId(superRole);// 角色
            searchCondition.setAgentId(opRealId);//当前人员id
            searchCondition.setOneOrgCode( logingMerchant.getOneagentid() );// 一级机构编号
            // 受理市场标识
            searchCondition.setGroupCdFlag( map.get("groupCd") );
            
			
	//		org();
		/*	//查询所属代理商
	        if(logingMerchant.getRoleType().equals(Role.AGENT.getCode())){
	        	operatorsList=merchantServices.listOperatorsAgent(logingMerchant.getOrgCode());
	        }else{
	        	operatorsList=merchantServices.listOperatorsAgent(null);
	        }*/
/*			if(searchCondition.getRole().equals("99")){
				searchCondition.setRole(Role.AGENT.getCode()+","+Role.O_MANAGER.getCode());   //操作员类型查询  代理商  和  O单管理员
			}*/
/*
			// 如果只查询直属代理商
			if(searchCondition.getIsDirectly().equals("0")){
				   searchCondition.setOpId(opRealId);
			}*/
	/*		//当登录人员为代理商时，查询他的子代理
			if(logingMerchant.getRoleType().equals(Role.AGENT.getCode()) || logingMerchant.getRoleType().equals(Role.AGENT_BUSS.getCode())){
				// 如果查询名下所有代理商
				String agentId= String.valueOf(logingMerchant.getId());
				searchCondition.setAgentId(agentId);
			} */
			String invoiceRateFlag = "0";
			// 如果当前登陆账号/上级账号是系统管理员，或当前登录账号是 市场人员 ，则允许显示发票扣率
			if(superRole.equals(Role.SYSTEM.getCode()) 
					|| superRole.equals(Role.MARKET_DIRECT.getCode())
					|| superRole.equals(Role.MARKET_LEAD.getCode())
					){
				invoiceRateFlag = "1";
			}
			//searchCondition.setStatus(OperatorsStatus.WAIT_AUDITING.getCode());  //查询代理商状态为  待审核   的
	/*		searchCondition.setOperators(logingMerchant);*/
			int rows=pagenitionService.countSQL(searchCondition);
			searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			 List<Object> searchRsList1=new ArrayList<Object>() ;
			
			
			if (searchRsList != null && searchRsList.size() > 0) {
				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					Operators sett = new Operators();
					if (obj[0] != null && !"".equals(obj[0])) {
						sett.setId(Long.valueOf(obj[0].toString()));
					}
					
					if (obj[1] != null && !"".equals(obj[1])) {
						sett.setAccountNo(obj[1].toString());
					}
					if (obj[2] != null && !"".equals(obj[2])) {
						sett.setRealName(obj[2].toString());
					}
					if (obj[3] != null && !"".equals(obj[3])) {
						sett.setSex(obj[3].toString());
					}
					if (obj[4] != null && !"".equals(obj[4])) {
						sett.setMobile(obj[4].toString());
					}
					if (obj[5] != null && !"".equals(obj[5])) {
						sett.setOrgCode(obj[5].toString());
					}
					if (obj[6] != null && !"".equals(obj[6])) {
						sett.setRoleType(obj[6].toString());
					}
					if (obj[7] != null && !"".equals(obj[7])) {
						sett.setSuperiorId(Long.valueOf(obj[7].toString()));
					}
					if (obj[8] != null && !"".equals(obj[8])) {
						sett.setCardNo(obj[8].toString());
					}
					if (obj[9] != null && !"".equals(obj[9])) {
						sett.setStatus(obj[9].toString());
					}
					
					if (obj[10] != null && !"".equals(obj[10])) {
						sett.setCompanyid(obj[10].toString());
					}
					if (obj[11] != null && !"".equals(obj[11])) {
						sett.setOneagentid(obj[11].toString());
					}
					if (obj[12] != null && !"".equals(obj[12])) {
						sett.setTaxRegistrationCertificate(InvoiceRateType.valueOfCode(obj[12].toString()).getName()); // 发票扣率
					}
					if (obj[13] != null && !"".equals(obj[13])) {
						sett.setOrganizationCode(obj[13].toString()); // 序号编码
					}
					if (obj[14] != null && !"".equals(obj[14])) {
						sett.setSuperiorName(obj[14].toString());
					}
					if (obj[15] != null && !"".equals(obj[15])) {
						sett.setCompanyName(obj[15].toString());
					}
					if (obj[16] != null && !"".equals(obj[16])) {
						sett.setOneagentName(obj[16].toString());
					}
					
					searchRsList1.add(sett);
				}
			}
			agentTheListSpecially(searchRsList1);
			

			setExcelName(new String(reportName.getBytes(), "ISO8859-1"));
			
			HSSFWorkbook work = excelService.exportAgentQueryInfoExcel(searchRsList1,searchCondition.getMinDate(),searchCondition.getMaxDate(), invoiceRateFlag);
			ByteArrayOutputStream output = new ByteArrayOutputStream();  
			work.write(output);  
			   
			byte[] ba = output.toByteArray();  
			excelFile = new ByteArrayInputStream(ba);  
			output.flush();  
			output.close(); 
			
		}  catch (Exception e) {
			logger.info("######导出" + reportName + "失败######");
			addActionError(e.getMessage());
			return ERROR;
		}/* finally {
			closeOutPut(output);
		}*/
		
		return SUCCESS;
	}
	/*
	@Action(value = "queryAgentViewInfo", results = { @Result(name = "success", location = "/pages/agent/agentView.jsp")
    })
	//查询代理商详细信息
	public String queryAgentViewAction(){
	Operators operators=new Operators();

	Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	try {
		operators=agentInfoService.queryAgentInfo(merchant.getAccountNo());
		// 页面分润比例转化,分润比例 * 100
		List<ProfitPercent> perList = getNewPreList(operators.getProfitPerList());
		operators.setProfitPerList(perList);
		// 主账号隐藏中间数字
		String bankAcctNo = Utils.dealCardNo(operators.getBankAcctNo());
		operators.setBankAcctNo(bankAcctNo);
		//		手机用*代替
		operators.setMobile(Utils.dealMobile(operators.getMobile()));
		//		身份证用*代替
		operators.setCardNo(Utils.dealCardNo(operators.getCardNo()));
		
		// 如果发票扣率不为空
		if ( null != operators.getTaxRegistrationCertificate() &&  !"".equals(operators.getTaxRegistrationCertificate()) ) {
			operators.setTaxRegistrationCertificate( InvoiceRateType.valueOfCode(operators.getTaxRegistrationCertificate()).getName() );
		}

		Map<String, String> map=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(), logingOperators.getRoleType(), logingOperators.getId(), logingOperators.getOrgCode());
        String superRole= map.get("superRole");
        
		String invoiceRateFlag = "0";
		// 如果 当前登陆账号/当前登录账号【如风控/清算】的上级角色 是系统管理员，或 当前登录账号 是 市场人员，则允许显示发票扣率
		if( superRole.equals(Role.SYSTEM.getCode()) 
				|| superRole.equals(Role.MARKET_DIRECT.getCode())
				|| superRole.equals(Role.MARKET_LEAD.getCode()) ) {
			invoiceRateFlag = "1";
		}
		getRequest().setAttribute("invoiceRateFlag", invoiceRateFlag);
		
		Map auditingMap=new HashMap();
		auditingMap.put(AuditingResultCodeType.PASS.getCode(),AuditingResultCodeType.PASS.getName());
		auditingMap.put(AuditingResultCodeType.REFUSE.getCode(),AuditingResultCodeType.REFUSE.getName());
		auditingMap.put(AuditingResultCodeType.INCOMPLETE_INFO.getCode(),AuditingResultCodeType.INCOMPLETE_INFO.getName());
		
		getRequest().setAttribute("auditingMap",auditingMap);
//		logger.info("map:"+ConfigProperties.getAgentTypeProperties()+"type:"+operators.getAgentType());
//		operators.setAgentType(ConfigProperties.getAgentTypeProperties().get(operators.getAgentType()));
		getRequest().setAttribute("agent", operators);
		
		Map<String,String> areaMap= ConfigProperties.getAreaCodeProperties();
		getRequest().setAttribute("areaName", areaMap.get(operators.getAreaCode()));
		
		
	} catch (Exception e) {
		logger.error(e.getMessage(),e);
		e.printStackTrace();
		addActionError(e.getMessage());
		return ERROR;
	}
	
	
	return SUCCESS;
	}
	*/
	//初始化加载页面
	/*@Action(value = "queryAgent", results = {
			@Result(name = "success", location = "/pages/agent/editAgent.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String  queryAgent(){
		List orgList=new ArrayList();
		try {
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			
			orgList = orgService.queryAllOrgList();
		
			Operators operator = powerInfoService.loadOperatorsById(new Long(code));
			if(null == operator){
				addActionError("加载代理商基本信息出错！！");
				return ERROR;
			}
			List<Object> audtingList=new ArrayList<Object>();
			audtingList=merinfoService.queryAuditingList(operator.getAccountNo());
			List<ProfitRule> ruleList = agentService.queryProfitRule(operator.getAccountNo());
			Map<String,ProfitRule> ruleMap = dealList(ruleList);
			
			List<ProfitPercent> perList = agentService.queryProfitPer(operator.getAccountNo());
			perList = getNewPreList(perList);
			operator.setProfitPerList(perList);
			

			Map<String, String> realMap=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(), logingOperators.getRoleType(), logingOperators.getId(), logingOperators.getOrgCode());
			String superRole= realMap.get("superRole");
            String opRealId =realMap.get("opRealId");

			Operators opRealOperator = powerInfoService.loadOperatorsById(new Long(opRealId));
			
			Map<String,String> mccMap = agentService.getMccArray4Agent(opRealOperator.getAccountNo(),opRealOperator.getRoleType());
			
			List<ProfitRule> list = getNewRuleList(mccMap, ruleMap);
			operator.setProList(list);
			
			String showFlag = "0";
			String invoiceRateFlag = "0";
			// 取代理商父类id
			Long supId = operator.getSuperiorId();
			// 取上级代理商信息
			Operators supOperator = powerInfoService.loadOperatorsById( supId );
			// 如果此代理商是当前登录账号下的直属代理商,或者 当前登陆账号为系统管理员  ,则允许修改
			if(logingOperators.getId() == supId ||
					opRealId.equals( String.valueOf(supId) ) ||
					superRole.equals( Role.SYSTEM.getCode() )
					|| ( String.valueOf(logingOperators.getId() ).equals( Constant.SHOUDANSHIYEBU_ID ) && operator.getOneagentid().equals( String.valueOf( operator.getId() ) )  )
					){
				showFlag = "1";
			}
			// 如果当前登陆账号是系统管理员[且该修改对象为机构管理员【一级代理商】]，则允许修改发票扣率
			if( ( superRole.equals( Role.SYSTEM.getCode() ) && 
					operator.getRoleType().equals( Role.O_MANAGER.getCode() ) )  
					|| ( String.valueOf(logingOperators.getId() ).equals( Constant.SHOUDANSHIYEBU_ID ) && operator.getOneagentid().equals( String.valueOf( operator.getId() ) )  )
					){
				invoiceRateFlag = "1";
			}
			operator.setSuperiorName(supOperator.getRealName());
			operator.setRoleName(Role.valueOfCode(operator.getRoleType()).getName());

			// 查询当前默认的模板信息
			ProfitModule bean = modelService.queryDefProfitModuleByAgentId(logingOperators.getId());
			int moduleSize = 0;
			if(null != bean){
				moduleSize = 1;
			}
			getRequest().setAttribute("moduleSize", moduleSize);
			
			getRequest().setAttribute("proListOld",ruleList);
			getRequest().setAttribute("audtingList", audtingList);
			getRequest().setAttribute("op",logingOperators);
			getRequest().setAttribute("agent",operator);
			getRequest().setAttribute("mccList",mccMap);
			getRequest().setAttribute("checkRuleMap",ruleMap.keySet());
			getRequest().setAttribute("perList",getDefPer());
			Map<String, String> map=dealAgentType(logingOperators.getFlag(), logingOperators.getAgentType(), ConfigProperties.getAgentTypeProperties());
			getRequest().setAttribute("agTypeList",map);
			getRequest().setAttribute("orgList", orgList);
			getRequest().setAttribute("areaList", ConfigProperties.getAreaCodeProperties());
			getRequest().setAttribute("showFlag", showFlag);
			getRequest().setAttribute("invoiceRateMap", InvoiceRateType.getAllEnumMap()); // 发票扣率
			getRequest().setAttribute("invoiceRateFlag", invoiceRateFlag);
			getRequest().setAttribute("superRole", superRole);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
			addActionError("加载代理商基本信息出错！！");
		}
		return SUCCESS;
	}*/
	
	/*
	//代理商信息变更
	@Action(value = "editAgent", results = {
			@Result(name = "success",type="redirect", location = "/agentQuery/queryAgentUnListJsp.ct"),
			@Result(name = "success2",type="redirect", location = "/agentQuery/agentSetInit.ct"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String  editAgent() throws Exception{
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Operators oldOP = powerInfoService.loadOperatorsById(agent.getId());
			agent.setOperators(logingOperators.getAccountNo());
			Date date=new Date();
			Long supId = oldOP.getSuperiorId();
			// 取上级代理商信息
			Operators supOperator = powerInfoService.loadOperatorsById( supId );

			Map<String, String> realMap=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(), logingOperators.getRoleType(), logingOperators.getId(), logingOperators.getOrgCode());
			String superRole= realMap.get("superRole");
            String opRealId =realMap.get("opRealId");
            
			// 如果此代理商是当前登录账号下的一级代理商,或者 当前登陆账号为系统管理员 ,则允许修改
			if(logingOperators.getId()==supId ||
					opRealId.equals( String.valueOf(supId) ) ||
					superRole.equals( Role.SYSTEM.getCode() )
							|| ( String.valueOf(logingOperators.getId() ).equals( Constant.SHOUDANSHIYEBU_ID ) && oldOP.getOneagentid().equals( String.valueOf( oldOP.getId() ) )  )
							 ){
				if(oldOP.getAccountNo()==null||"".equals(oldOP.getAccountNo().trim())){
					addActionError("代理商对应账号不存在,无法修改");
				}else{
					if( !Utils.checkAccountName( agent.getRealName() ) ) {
						addActionError("名称格式不正确，只能输入中英文，数字，括号和空格!");
						return ERROR;
					}
					String isUseDefModule = agent.getIsUseDefModule();
					if(null != isUseDefModule && !isUseDefModule.equals("")){
						// 查询当前默认的模板信息
						ProfitModule bean = modelService.queryDefProfitModuleByAgentId( logingOperators.getId());
						
						// 如果查询模板id为空,返回异常
						if(null == bean){
							addActionError("代理申请失败,默认分润模板不存在,请重新添加或设置默认模板!");
							return ERROR;
						}
					}
				//	agentService.deleteProfitRuleByAgentId(oldOP.getAccountNo());
					agent.setValidStartDate(DateUtil.initStartDate(date));
					agent.setValidEndDate(DateUtil.initEndDate());
					agentService.editAgent(agent,oldOP,logingOperators);
				}
			}
			else{
				addActionError("数据修改权限不够");
			}
			
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		if("1".equals(updateFlag)){
			 getRequest().setAttribute("msg", "代理商信息修改成功！");
			 return "success2";
		}
		 getRequest().setAttribute("msg", "代理商信息补全资料成功！");
		 return "success";
	}*/
	
	//查询机构
	public void org() throws Exception{
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		String invoiceRateFlag = "0";
		
		//orgList=orgService.listOrgs(logingOperators);
		/*orgList=orgService.queryOrgList();*/

		orgList = orgService.queryAllOrgList();
		getRequest().setAttribute("orgList", orgList);
		
		Map<String, String> map=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(), logingOperators.getRoleType(), logingOperators.getId(), logingOperators.getOrgCode());
        String superRole= map.get("superRole");
		
			
		//加载角色类型 
		Map<String,String> roleMap=new LinkedHashMap<String,String>();
		if( superRole.equals(Role.SYSTEM.getCode()) 
				|| superRole.equals(Role.MARKET_DIRECT.getCode()) 
				|| superRole.equals(Role.MARKET_LEAD.getCode())){
			roleMap.put(Role.O_MANAGER.getCode(),Role.O_MANAGER.getName());
		//	roleMap.put(Role.AGENT.getCode(),Role.AGENT.getName());
		} else if (superRole.equals(Role.AGENT.getCode())){
			roleMap.put(Role.AGENT.getCode(),Role.AGENT.getName());
		}
		roleMap.put(Role.AGENT_BUSS.getCode(),Role.AGENT_BUSS.getName());//业务员

		// 如果当前登陆账号/上级账号 是系统管理员，或 当前账号是 市场人员，则允许显示发票扣率
		if(superRole.equals(Role.SYSTEM.getCode()) 
				|| superRole.equals(Role.MARKET_DIRECT.getCode())
				|| superRole.equals(Role.MARKET_LEAD.getCode()) 
				){
			invoiceRateFlag = "1";
		}

		getRequest().setAttribute("roleMap",roleMap);
		getRequest().setAttribute("isDirectlyMap",Utils.getIsDirectlyMap());
		getRequest().setAttribute("invoiceRateFlag", invoiceRateFlag);
		
	}
	
	protected void agentTheListSpecially(List<Object> list) {
    	List<Object> tempList=new ArrayList<Object>();
		for(Object obj:list){
			Operators temp=(Operators)obj;
			for(TblInsInf bean:orgList){
				if(temp.getOrgCode().equals(bean.getInsIdCd())){
					temp.setOrgName(bean.getInsName());
				}
			}
			/*
			for (Operators opera : operatorsList) {
				// 分公司名称
				if(String.valueOf(opera.getId()).equals(temp.getCompanyid())){
					temp.setCompanyName(opera.getRealName());
				}
				// 一级代理商名称
				if(String.valueOf(opera.getId()).equals(temp.getOneagentid())){
					temp.setOneagentName(opera.getRealName());
				}
				
				if(opera.getId() == temp.getSuperiorId()){
					temp.setSuperiorName(opera.getRealName());
				}
			}*/

			//		手机用*代替
			temp.setMobile(Utils.dealMobile(temp.getMobile()));
			//		身份证用*代替
			temp.setCardNo(Utils.dealCardNo(temp.getCardNo()));
			
			temp.setSex(SexStatus.valueOfCode(temp.getSex()).getName());
			temp.setRoleName(Role.valueOfCode(temp.getRoleType()).getName());
			temp.setStatus(OperatorsStatus.valueOfCode(temp.getStatus()).getName());
			tempList.add(temp);
		}
		searchRsList=tempList;
		
	}
	
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (AgentUnQuerySearchCondition)getSession().getAttribute(SEARCH_SESSION_BEAN_AGENT_QUERY_INFO);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_AGENT_QUERY_INFO, searchCondition);
	}

	public Operators getMerchant() {
		return merchant;
	}

	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}

	public AgentUnQuerySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(AgentUnQuerySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	public SerialNumQueryCondition getSerialNumCondition() {
		return serialNumCondition;
	}

	public void setSerialNumCondition(SerialNumQueryCondition serialNumCondition) {
		this.serialNumCondition = serialNumCondition;
	}

	public AuditingItem getAuditing() {
		return auditing;
	}

	public void setAuditing(AuditingItem auditing) {
		this.auditing = auditing;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public List<Operators> getOperatorsList() {
		return operatorsList;
	}

	public void setOperatorsList(List<Operators> operatorsList) {
		this.operatorsList = operatorsList;
	}
	
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}/*

	@Action(value = "serialNumQuery", results = { @Result(name = "success", location = "/pages/agent/serialNumQuery.jsp")
    })
    
	//查询终端号初始化
	public String serialNumQuery(){
		
		Operators loginOperator = (Operators) ActionContext.getContext()
		.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
	
	try {
		System.out.println("code"+code);
		orgList = orgService.queryOrgList();
		getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));
		getRequest().setAttribute("nameMap", "");
		getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));		
		//List yjPosAgentlist = merchantServices.queryYjPosAgent(code);
		//getRequest().setAttribute("yjPosAgentlist",yjPosAgentlist);
		
	} catch (Exception e) {
		logger.error(e.getMessage(),e);
		e.printStackTrace();
		addActionError(e.getMessage());
		return ERROR;
	}
	return SUCCESS;
	}*/
	
	public List<ProfitRule> getNewRuleList(Map<String,String> mccMap,Map<String,ProfitRule> ruleMap){
		List<ProfitRule> ruleListNew  = new ArrayList<ProfitRule>();
		
		for(Map.Entry<String, String> entry : mccMap.entrySet()) {
			String key = entry.getKey();
			ProfitRule pro = ruleMap.get(key);
			if(pro==null){
				/*pro = new ProfitRule();
				pro.setIsCheck("0");
				pro.setMccTypeName(mccMap.get(key));
				pro.setMccTypeCode(key);	
				*/
			}
			ruleListNew.add(pro);
		}
		return ruleListNew;
		
	}
	public List<ProfitPercent> getNewPreList(List<ProfitPercent> perList){
		List<ProfitPercent> perListNew  = new ArrayList<ProfitPercent>();
		for (ProfitPercent per : perList) {
			String percentStr = per.getPercent();
			Double perDouble = Double.parseDouble(percentStr) * 100;
			// double 转 int 类型,便于页面显示
			BigDecimal b = new BigDecimal(perDouble);
			int percent = b.intValue();
			
			per.setPercent(percent + "");
			perListNew.add(per);
		}
		return perListNew;
	}
	
	
	public Map<String,ProfitRule> dealList(List<ProfitRule> ruleList){
		Map<String,ProfitRule> backMap = new LinkedHashMap<String, ProfitRule>();
		
		for(ProfitRule pro:ruleList){/*
			String id = pro.getMccTypeCode()+"-"+pro.getParamName1();*/
			String id = pro.getMccTypeCode();
			pro.setIsCheck("1");
			backMap.put(id,pro);
		}
		return backMap;
		
	}
	

	public Operators getAgent() {
		return agent;
	}

	public void setAgent(Operators agent) {
		this.agent = agent;
	}

	public String getUpdateFlag() {
		return updateFlag;
	}

	public void setUpdateFlag(String updateFlag) {
		this.updateFlag = updateFlag;
	} 

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}  
	
	public HashMap<String,String> getDefPer(){
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("01", "01");
		map.put("02", "02");
		map.put("03", "03");
		map.put("04", "04");
		return map;
	}

}
